package org.mzyyn.qr.util;

import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * UserUtils
 *
 * @author lipeng
 * @version 1.0.0
 * @classname UserUtils
 * @description 用户加解密工具
 * @date 2024 /5/14 13:05
 */
@Slf4j
public class EncryptUtils {
    private static final String ENC_STR_SALT_PREFIX = "enc:0530";

    private static final String RANDOM_VAL = "243892";

    private static final String RANDOM_KEY_VAL = "0uJvadeIyP8sft7D6spAyb2YqAo2sFCH";

    private static final String DEFAULT_SALT = "388472";

    /**
     * 加密
     * @param encStr
     * @return
     */
    public static String aesEncrypt(String encStr){
        return SecureUtil.aes(getKey(getSalt(encStr)).getBytes()).encryptHex(encStr);
    }

    /**
     * 解密
     * @param aecStr
     * @param salt
     * @return
     */
    public static String aesDecrypt(String aecStr, String salt){
        return SecureUtil.aes(getKey(salt).getBytes()).decryptStr(aecStr);
    }

    /**
     * 加密
     * @param encStr
     * @return
     */
    public static String aesEncryptDefault(String encStr){
        return SecureUtil.aes(getKey(getDefaultSalt()).getBytes()).encryptHex(encStr);
    }

    /**
     * 解密
     * @param aecStr
     * @return
     */
    public static String aesDecryptDefault(String aecStr){
        return SecureUtil.aes(getKey(getDefaultSalt()).getBytes()).decryptStr(aecStr);
    }


    /**
     * md5加密
     * @param s
     * @return
     */
    public static final String md5(String s) {
        return SecureUtil.md5(s);
    }

    public static void main(String[] args) {
        String phone = "18888888887";

        String s = aesEncrypt(phone);
        System.out.println(s);

        String s1 = aesDecrypt(s, getSalt(phone));
        System.out.println(s1);

        String s2 = aesDecrypt("12345123", getSalt("156123412314"));
        System.out.println(s2);
    }

    /**
     * 获取字串盐，用作加密
     * @param encStr
     * @return
     */
    public static String getSalt(String encStr){
        return SecureUtil.md5(ENC_STR_SALT_PREFIX + encStr + RANDOM_VAL);
    }

    /**
     * 获取字串盐，用作加密
     * @return
     */
    public static String getDefaultSalt(){
        return SecureUtil.md5(ENC_STR_SALT_PREFIX + DEFAULT_SALT + RANDOM_VAL);
    }
    /**
     * 通过盐获取加密key
     * @param salt
     * @return
     */
    private static String getKey(String salt){
        return SecureUtil.md5(RANDOM_KEY_VAL + salt);
    }
}
